//
//  ProblemHandleViewController.m
//  Utils
//
//  Created by enghou on 2018/4/16.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "ProblemHandleViewController.h"
#import "ProblemDoneHandleViewController.h"
#import "ProblemFetchViewController.h"
#import "ProblemUpViewController.h"
#import "ProblemBackViewController.h"
@interface ProblemHandleViewController ()<WechatShortVideoDelegate,HandleAudio>

@end

@implementation ProblemHandleViewController

-(UITableView *)generateTableView{
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableFooterView = self.tableFooter;
    return tableView;
}

-(NSDictionary *)param{
    if (self.type == 0) {
        if ([self.textView.text length] == 0) {
            [self alertSome:@"请输入办理意见!"];
            return nil;
        }
        return @{@"logNew.content":self.textView.text,@"issueStepId":self.stepId};
    }else if(self.type == 1){
        if ([self.textView.text length] == 0) {
            [self alertSome:@"请输入办理意见!"];
            return nil;
        }
        if ([self.typeId isEqualToString:@"10"]) {
            return @{@"content":self.textView.text,@"stepRecordId":self.stepId,@"appealId":self.eventId,@"operationCode":@"2050"};
        }else{
            return @{@"content":self.textView.text,@"stepRecordId":self.stepId,@"appealId":self.eventId,@"operationCode":@"2070"};
        }
    }
    return nil;
}

-(void)uploadFilesSuccessBlock:(void(^)(NSArray *))complete{
    __block NSInteger maxTask = 0;
    __block NSInteger taskCompleteCount = 0;
    NSMutableArray *files = [NSMutableArray array];
    NSMutableArray *ims = [NSMutableArray array];
    [self.images enumerateObjectsUsingBlock:^(UIImage *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.size.width > 0) {
            if (idx == 0) {
                maxTask++;
            }
            NSData *data = UIImageJPEGRepresentation(obj, 0.1);
            [ims addObject:data];
        }
    }];
    NSMutableArray *videos = [NSMutableArray array];
    [self.videos enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.absoluteString length] > 0) {
            NSData *data = [NSData dataWithContentsOfFile:obj.path];
            if (data) {
                if (idx == 0) {
                    maxTask++;
                }
                [videos addObject:data];
            }
        }
    }];
    NSMutableArray *audios = [NSMutableArray array];
    [self.audios enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.absoluteString length] > 0) {
            NSData *data = [NSData dataWithContentsOfFile:obj.path];
            if (data) {
                if (idx == 0) {
                    maxTask++;
                }
                [audios addObject:data];
            }
        }
    }];
    if ([videos count] > 0) {
        NSLog(@"videos = %@",videos);
        [self beginLoading];
        [[NetWorkerManager sharedInstance]uploadVideoWithPath:kUploadFilePath parameter:nil files:videos fileName:@"file" suffix:@"mp4" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if ([audios count] > 0) {
        NSLog(@"audios = %@",audios);
        [[NetWorkerManager sharedInstance]uploadVideoWithPath:kUploadFilePath parameter:nil files:videos fileName:@"file" suffix:@"mp4" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if ([ims count] > 0) {
        NSLog(@"images = %@",ims);
        [self beginLoading];
        [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:ims fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
            [self endLoading];
            BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:NSClassFromString(@"FileItemModel")];
            if (model.success) {
                taskCompleteCount++;
                [files addObjectsFromArray:model.list];
                if (taskCompleteCount == maxTask) {
                    complete(files);
                }
            }
        } failBlock:^(NSInteger code) {
            [self endLoading];
        }];
    }
    if (maxTask == 0) {
        complete(@[]);
    }
}

-(void)recordAction{
    AudioViewController *audioVC = [[AudioViewController alloc]init];
    audioVC.delegate = self;
    self.definesPresentationContext = YES;
    UIColor *color = [UIColor blackColor];
    audioVC.view.backgroundColor = [color colorWithAlphaComponent:0.5];
    audioVC.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [(BaseViewController *)self.theDelete presentViewController:audioVC animated:YES completion:nil];
}

-(void)playAudioWithURL:(NSURL *)url{
    PlayAudioViewController *play = [[PlayAudioViewController alloc]init];
    play.url = url;
    self.definesPresentationContext = YES;
    play.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    play.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [(BaseViewController *)self.theDelete presentViewController:play animated:NO completion:nil];
}

-(void)playVideoWithURL:(NSURL *)url{
    AVPlayerViewController *VC = [[AVPlayerViewController alloc]init];
    VC.player = [[AVPlayer alloc] initWithURL:url];
    VC.videoGravity = AVLayerVideoGravityResizeAspect;
    [(BaseViewController *)self.theDelete presentViewController:VC animated:NO completion:nil];
}

-(void)chooseVideoAction{
    WechatShortVideoController *wechatShortVideoController = [[WechatShortVideoController alloc] init];
    wechatShortVideoController.delegate = self;
    [(BaseViewController *)self.theDelete presentViewController:wechatShortVideoController animated:YES completion:nil];
}

-(void)chooseImageAction{
    TZImagePickerController *picker = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:nil];
    __weak typeof(self) wself = self;
    picker.didFinishPickingPhotosWithInfosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto, NSArray<NSDictionary *> *infos) {
        [wself.selectedBtn setImage:[photos objectAtIndex:0] forState:UIControlStateNormal];
        [wself.images replaceObjectAtIndex:[wself.sourceBtns indexOfObject:wself.selectedBtn] withObject:photos[0]];
        UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [delBtn setImage:[UIImage imageNamed:@"icon_off"] forState:UIControlStateNormal];
        delBtn.frame = CGRectMake(92, 0, 28, 28);
        delBtn.tag = 1001;
        [wself.selectedBtn addSubview:delBtn];
        [delBtn addTarget:wself action:@selector(deleteSource:) forControlEvents:UIControlEventTouchUpInside];
    };
    [(BaseViewController *)self.theDelete presentViewController:picker animated:YES completion:nil];
}

-(void)showActions{
    NSArray *dicts;
    if (self.type == 0) {
        dicts = @[@{@"code":@"10",@"name":@"办理"},@{@"code":@"30",@"name":@"结案"},@{@"code":@"50",@"name":@"上报"},@{@"code":@"70",@"name":@"交办"},@{@"code":@"90",@"name":@"回退"}];
    }else{
        dicts = @[@{@"code":@"10",@"name":@"办理"},@{@"code":@"30",@"name":@"办结"},@{@"code":@"50",@"name":@"上报"},@{@"code":@"70",@"name":@"交办"},@{@"code":@"90",@"name":@"回退"}];
    }
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleAlert];
    for (NSString *code in self.actions) {
        [dicts enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString *c = [obj objectForKey:@"code"];
            if ([c isEqualToString:code]){
                UIAlertAction *action = [UIAlertAction actionWithTitle:[obj objectForKey:@"name"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeNot" object:c];
                }];
                [alert addAction:action];
            }
        }];
    }
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [(BaseViewController *)self.theDelete presentViewController:alert animated:YES completion:nil];
}

-(void)deleteSource:(UIButton *)delBtn{
    UIButton *supBtn = (UIButton *)delBtn.superview;
    [supBtn setImage:[UIImage imageNamed:@"icon_upload"] forState:UIControlStateNormal];
    NSInteger index = [self.sourceBtns indexOfObject:supBtn];
    UIImage *selectedImage = [self.images objectAtIndex:index];
    if (selectedImage.size.width > 0) {
        UIImage *image = [[UIImage alloc]init];
        [self.images replaceObjectAtIndex:index withObject:image];
        [delBtn removeFromSuperview];
        return;
    }
    NSURL *url = [self.videos objectAtIndex:index];
    if ([url.absoluteString length] > 0) {
        [[NSFileManager defaultManager]removeItemAtURL:url error:nil];
        NSURL *file = [NSURL URLWithString:@""];
        [self.videos replaceObjectAtIndex:index withObject:file];
        [delBtn removeFromSuperview];
        return;
    }
    NSURL *audioURL = [self.audios objectAtIndex:index];
    if ([audioURL.absoluteString length] > 0) {
        [[NSFileManager defaultManager]removeItemAtURL:url error:nil];
        NSURL *file = [NSURL URLWithString:@""];
        [self.audios replaceObjectAtIndex:index withObject:file];
        [delBtn removeFromSuperview];
        return;
    }
}

-(void)showImageWithImage:(UIImage *)image view:(UIView *)view{
    NSMutableArray *browseItemArray = [[NSMutableArray alloc]init];
    int i = 0;
    for(i = 0;i < [self.images count];i++)
    {
        UIImage *image = self.images[i];
        if (image.size.width > 0) {
            MSSBrowseModel *browseItem = [[MSSBrowseModel alloc]init];
            browseItem.bigImage = image;
            browseItem.smallImageView = self.sourceBtns[i];
            [browseItemArray addObject:browseItem];
        }
    }
    MSSBrowseLocalViewController *bvc = [[MSSBrowseLocalViewController alloc]initWithBrowseItemArray:browseItemArray currentIndex:[self.sourceBtns indexOfObject:view]];
    bvc.presentVC = self.navigationController;
    [bvc showBrowseViewController];
}

- (IBAction)showFilePicker:(id)sender {
    NSInteger index = [self.sourceBtns indexOfObject:sender];
    UIImage *selectedImage = [self.images objectAtIndex:index];
    if (selectedImage.size.width > 0) {
        [self showImageWithImage:selectedImage view:sender];
        return;
    }
    NSURL *url = [self.videos objectAtIndex:index];
    if ([url.absoluteString length] > 0) {
        [self playVideoWithURL:url];
        return;
    }
    NSURL *audioURL = [self.audios objectAtIndex:index];
    if ([audioURL.absoluteString length] > 0) {
        [self playAudioWithURL:audioURL];
        return;
    }
    _selectedBtn = sender;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *record = [UIAlertAction actionWithTitle:@"录音" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self recordAction];
    }];
    [alert addAction:record];
    UIAlertAction *video = [UIAlertAction actionWithTitle:@"视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseVideoAction];
    }];
    [alert addAction:video];
    UIAlertAction *image = [UIAlertAction actionWithTitle:@"照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self chooseImageAction];
    }];
    [alert addAction:image];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:cancel];
    [(BaseViewController *)self.theDelete presentViewController:alert animated:YES completion:nil];
}

-(UITableView *)tableForSubClassName:(NSString *)name{
    ProblemHandleViewController *vc = (ProblemHandleViewController *)[VCLoader vcWithName:name];
    return vc.tableView;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.images = [NSMutableArray array];
    for (int i = 0; i < 3; i ++) {
        UIImage *image = [[UIImage alloc]init];
        [self.images addObject:image];
    }
    self.audios = [NSMutableArray array];
    for (int i = 0; i < 3; i ++) {
        NSURL *audio = [NSURL URLWithString:@""];
        [self.audios addObject:audio];
    }
    self.videos = [NSMutableArray array];
    for (int i = 0; i < 3; i ++) {
        NSURL *video = [NSURL URLWithString:@""];
        [self.videos addObject:video];
    }
    
    self.tableFooter = self.tableView.tableFooterView;
    
    self.dateField = [[UITextField alloc]init];
    [self.view addSubview:self.dateField];
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 240)];
    self.datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    self.datePicker.backgroundColor = [UIColor whiteColor];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    self.datePicker.minimumDate = [NSDate date];
    self.dateField.inputView = self.datePicker;
    self.dateField.inputAccessoryView = [self inputAccessView];
}

//上传数据
//-(void)doEventWithFiles:(NSArray *)files{
//    [self beginLoading];
//    [[NetWorkerManager sharedInstance]handleProblemWithCode:self.typeId param:[self param] successBlock:^(BaseModel *model) {
//        [self endLoading];
//        if (model.success) {
//            [self pop];
//        }else{
//            [self alertSome:model.msg];
//        }
//    } failBlock:^(NSInteger code) {
//        [self endLoading];
//        [self alertSome:kNetWorkFail];
//    }];
//}

//-(NSString *)typeId{
//    return @"10";
//}

-(void)doneAction{
    //先要上传
//    [self uploadFilesSuccessBlock:^(NSArray *files){
//        //上传参数
//        [self doEventWithFiles:files];
//    }];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            [self showActions];
            break;
        default:
            break;
    }
}


#pragma mark - videodelegate
-(UIImage*)getVideoPreViewImageWithPath:(NSURL *)videoPath
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoPath options:nil];
    AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    gen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 600);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *img = [[UIImage alloc]initWithCGImage:image];
    CGImageRelease(image);
    return img;
}

#pragma mark - Video And Audio Delegate
-(void)finishWechatShortVideoCapture:(NSURL *)filePath{
    NSInteger index = [self.sourceBtns indexOfObject:self.selectedBtn];
    [self.videos replaceObjectAtIndex:index withObject:filePath];
    UIImage *image = [self getVideoPreViewImageWithPath:filePath];
    [self.selectedBtn setImage:image forState:UIControlStateNormal];
    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setImage:[UIImage imageNamed:@"icon_off"] forState:UIControlStateNormal];
    delBtn.frame = CGRectMake(92, 0, 28, 28);
    [self.selectedBtn addSubview:delBtn];
    delBtn.tag = 1001;
    [delBtn addTarget:self action:@selector(deleteSource:) forControlEvents:UIControlEventTouchUpInside];
    
}

-(void)handleAudioWithFilePath:(NSURL *)filepath{
    NSInteger index = [self.sourceBtns indexOfObject:self.selectedBtn];
    [self.audios replaceObjectAtIndex:index withObject:filepath];
    [self.selectedBtn setImage:[UIImage imageNamed:@"icon_audio"] forState:UIControlStateNormal];
    UIButton *delBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [delBtn setImage:[UIImage imageNamed:@"icon_off"] forState:UIControlStateNormal];
    delBtn.frame = CGRectMake(92, 0, 28, 28);
    delBtn.tag = 1001;
    [self.selectedBtn addSubview:delBtn];
    [delBtn addTarget:self action:@selector(deleteSource:) forControlEvents:UIControlEventTouchUpInside];
}


-(void)dealloc{
    [self.audios enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.path length] > 0) {
            [[NSFileManager defaultManager]removeItemAtPath:obj.path error:nil];
        }
    }];
    [self.videos enumerateObjectsUsingBlock:^(NSURL *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.path length] > 0) {
            [[NSFileManager defaultManager]removeItemAtPath:obj.path error:nil];
        }
    }];
}
@end
